<template>
  <el-dialog
    append-to-body
    :close-on-click-modal="false"
    :before-close="crud.cancelCU"
    :visible="crud.status.cu > 0"
    :title="crud.status.title"
    width="500px"
    @close="handleClose"
  >
    <el-form
      label-width="100px"
      size="small"
      ref="form"
      :model="form"
      :rules="rules"
    >
      <el-form-item label="门店名称" prop="storeName">
        <el-input v-model="form.storeName" placeholder="请输入门店名称" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status">
          <el-option :value="0" label="正常"></el-option>
          <el-option :value="1" label="无效"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入联系电话"/>
      </el-form-item>
      <el-form-item label="省市区" prop="province">
        <el-cascader
          ref="cascader"
          placeholder="请选择"
          v-model="cascaderValue"
          @change="handleChange"
          style="width: 100%"
          :options="options"
          :props="regionProps"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入详细地址"/>
      </el-form-item>
      <!-- <el-form-item label="门店二维码" prop="storeEwm">
        <el-upload
          :show-file-list="false"
          :on-success="handleSuccess"
          :on-error="handleError"
          :headers="headers"
          :action="uploadApi"
          :before-upload="beforeUpload"
          class="storeEwm-uploader"
        >
          <img :src="form.storeEwm" title="点击上传二维码" class="avatar">
        </el-upload>
      </el-form-item> -->
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="crud.cancelCU">取消</el-button>
      <el-button :loading="crud.procesLoading" type="primary" @click="crud.submitCU">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import CRUD, { form } from '@crud/crud';
import { queryLazyTree } from "@/api/charges/logistics";
import { getToken } from '@/utils/auth';
import { mapGetters } from 'vuex'

const regionCache = {};
const defaultForm = {
  address: "",
	area: "",
	city: "",
	phone: "",
	province: "",
	status: 0,
	storeName: "",
  storeEwm: ""
}

export default {
  name: "storeForm",
  mixins: [ form(defaultForm) ],
  data() {
    return {
      rules: {
        storeName: [
          { required: true, message: '请输入门店名称', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请选择省市区', trigger: 'blur' }
        ]
      },
      regionProps: {
        lazy: true,
        lazyLoad(node, resolve) {
          let parent = node.value || "00";
          if(regionCache[parent]) {
            resolve(regionCache[parent]);
            return;
          }
          queryLazyTree(node.value || "00").then(res => {
            let data = [];
            let level = node.level;
            res.forEach(item => {
              data.push({
                value: item.value,
                label: item.title,
                leaf: level >= 2
              });
            });
            regionCache[parent] = data;
            resolve(data);
          });
        }
      },
      headers: {
        'Authorization': getToken()
      },
      cascaderValue: [],
      options: []
    }
  },
  computed: {
    ...mapGetters([
      'uploadApi'
    ]),
  },
  created() {
    this._loadLazyTree({
      children: this.options,
      parent: "00"
    });
  },
  methods: {
    [CRUD.HOOK.afterToEdit]() {
      let { provinceCode,cityCode,areaCode } = this.form;
      this.cascaderValue = [ provinceCode,cityCode,areaCode ];

      this.$nextTick(() => {
        let cascader = this.$refs["cascader"];
        if(cascader) {
          cascader.panel.activePath = []; 
          cascader.panel.loadCount = 0;
          cascader.panel.lazyLoad();
        }
      });
    },
    handleChange() {
      let nodes = this.$refs.cascader.getCheckedNodes()[0].pathLabels;
      this.form.province = nodes[0];
      this.form.city = nodes[1];
      this.form.area = nodes[2];

      this.form.provinceCode = this.cascaderValue[0];
      this.form.cityCode = this.cascaderValue[1];
      this.form.areaCode = this.cascaderValue[2];
    },
    handleClose() {
      this.cascaderValue = [];
    },
    handleSuccess(response) {
      this.$notify({
        title: '上传成功',
        type: 'success',
        duration: 2500
      })
      this.form.storeEwm = response.link;
    },
    handleError(e) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
    },
    beforeUpload(file) {
      let isJPG = (file.type === 'image/jpeg'
      || file.type === 'image/jpg' || file.type === 'image/png');
      let isLt2M = file.size / 1024 / 1024 < 1;

      if (!isJPG) {
        this.$message.error('请选择 JPG/PNG 格式图片!');
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 1MB!');
      }
      return isJPG && isLt2M;
    },
    _loadLazyTree({ parent, children}) {
      queryLazyTree(parent).then(res => {
        res.forEach(item => {
          children.push({
            value: item.value,
            label: item.title
          });
        });
      });
    }
  }
}
</script>

<style lang="scss">
.storeEwm-uploader {
  .avatar {
    border-radius: 0;
    height: 120px;
    width: 120px;
  }
}
</style>